/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.github.xiaoymin.deploy.plugin.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.deploy.DeployHelperConnection;
import com.github.xiaoymin.deploy.common.PluginConst;
import com.github.xiaoymin.deploy.model.DeployHelperDeploy;
import com.github.xiaoymin.deploy.model.DeployRequest;
import com.github.xiaoymin.deploy.plugin.DeployService;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 停止远程服务步骤
 * <ul>
 *     <li>判断当前执行停止Shell脚本是否为空,如果Shell脚本不为空,则判断文件是否存在,存在则执行,不存在抛出异常</li>
 *     <li>如果当前停止Shell脚本为空,判断processName是否为空,不为空则使用默认停止Shell脚本,进行停止服务</li>
 * </ul>
 * @since:deploy-helper 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2020/07/05 13:02
 */
public class StopService implements DeployService {

    Logger logger= LoggerFactory.getLogger(StopService.class);

    @Override
    public boolean action(DeployRequest deployRequest) {
        //执行stop脚本
        logger.info("StopService Run...");
        DeployHelperConnection connection=deployRequest.getConnection();
        DeployHelperDeploy helperDeploy=deployRequest.getHelperDeploy();
        MavenProject mavenProject=deployRequest.getMavenProject();
        try{
            if (StrUtil.isNotBlank(helperDeploy.getStopShell())){
                //远程stop脚本存在,直接执行
                logger.info("Stop Shell Exists,Now Stop Remote Process");
                if (!connection.exists(helperDeploy.getStopShell())){
                    throw new RuntimeException("stopShell don't exists");
                }
                String stopCommand="sh "+helperDeploy.getStopShell();
                connection.shell(stopCommand,true);
            }else{
                //远程stop脚本不存在,但是processName存在,根据processName
                logger.info("Stop Shell is Empty");
                String targetDir= StrUtil.subBefore(helperDeploy.getTarget(),"/",true);
                connection.mkdir(targetDir,true);
                String currentStopShellContent=stopDefaultShell(helperDeploy.getProcessName());
                File sourceFile=new File(mavenProject.getBasedir()+File.separator+"deployStop.sh");
                FileUtil.writeString(currentStopShellContent,sourceFile,"UTF-8");
                String targetPath=targetDir+"/"+"deployStop.sh";
                logger.info("sourcePath:{},targetPath:{}",sourceFile.getAbsolutePath(),targetPath);
                List<String> shells=new ArrayList<>();
                //判断是否存在
                if (!connection.exists(targetPath)){
                    connection.upload(sourceFile.getAbsolutePath(),targetPath);
                    shells.add("chmod a+x "+targetPath);
                }
                shells.add("sh "+targetPath);
                connection.shell(shells,true);
                sourceFile.delete();
            }
            return true;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public String getPluginName() {
        return PluginConst.PLUGIN_STOP_SERVICE;
    }

    /**
     * 获取默认停止Shell脚本
     * @param processName 进程名称
     * @return 返回默认stopShell脚本内容
     */
    private String stopDefaultShell(String processName){
        StringBuilder stringBuilder=new StringBuilder();
        //判断进程是否存在,如果进程存在则删除进程
        stringBuilder.append("echo \"Stop Procedure : "+processName+"\"").append("\n");
        stringBuilder.append("pid=`ps -ef |grep java|grep "+processName+"|awk '{print $2}'`").append("\n");
        stringBuilder.append("echo 'old Procedure pid:'$pid").append("\n");
        stringBuilder.append("if [ -n \"$pid\" ]").append("\n");
        stringBuilder.append("then").append("\n");
        stringBuilder.append("kill $pid").append("\n");
        stringBuilder.append("fi");
        return stringBuilder.toString();
    }
}
